--CALCULO ICMS-ST

DECLARE 
@VALOR_ICMS NUMERIC(14,2),
@VALOR_IPI NUMERIC(14,2),
@BASE_ICMS NUMERIC(14,2),
@BASE NUMERIC(14,2),
@X NUMERIC(14,2),
@Y NUMERIC(14,2),
@IVA NUMERIC(14,4),
@ALIQUOTA_ICMSST NUMERIC(14,2),
@NF_NUMERO VARCHAR(6)

-- INFORMAR O taxa de IVA E O NUMERO DA NF
SET @IVA = 45.54
SET @NF_NUMERO = '000042'

SELECT @VALOR_ICMS = SUM(ISNULL(B.VALOR_IMPOSTO,0)), @BASE_ICMS = SUM(ISNULL(B.BASE_IMPOSTO,0)) FROM FATURAMENTO A
JOIN FATURAMENTO_IMPOSTO B
ON A.NF_SAIDA = B.NF_SAIDA
WHERE A.NF_SAIDA = @NF_NUMERO
AND B.ID_IMPOSTO = '1'

SELECT @VALOR_IPI = SUM(ISNULL(B.VALOR_IMPOSTO,0)) FROM FATURAMENTO A
JOIN FATURAMENTO_IMPOSTO B
ON A.NF_SAIDA = B.NF_SAIDA
WHERE A.NF_SAIDA = @NF_NUMERO
AND B.ID_IMPOSTO = '2'

SELECT @ALIQUOTA_ICMSST = B.TAXA_IMPOSTO/100 FROM FATURAMENTO A
JOIN FATURAMENTO_IMPOSTO B
ON A.NF_SAIDA = B.NF_SAIDA
WHERE A.NF_SAIDA = @NF_NUMERO
AND B.ID_IMPOSTO = '12'

SET @BASE = @BASE_ICMS + @VALOR_IPI
SET @X = @BASE*(@IVA/100)
SET @Y = (@X+@BASE)*@ALIQUOTA_ICMSST

SELECT 'BASE ICMS-ST' = @BASE, 'ICMS-ST' = @Y-@VALOR_ICMS 


